package com.guigu.servicegoods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guigu.common_util.pojo.utils.Result;
import com.guigu.servicegoods.domain.TbCategoryBrand;
import com.guigu.servicegoods.mapper.TbCategoryBrandMapper;
import com.guigu.servicegoods.service.TbCategoryBrandService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-07-08
 */
@Service
public class TbCategoryBrandServiceImpl extends ServiceImpl<TbCategoryBrandMapper, TbCategoryBrand> implements TbCategoryBrandService {

    @Override
    public Result findPage(Map<String, Object> searchMap, Integer page, Integer size) {
        QueryWrapper<TbCategoryBrand> wrapper = createExample(searchMap);
        //创建page对象
        Page<TbCategoryBrand> pageCategoryBrand = new Page<>(page,size);
        baseMapper.selectPage(pageCategoryBrand,wrapper);
        return Result.ok().data("row",pageCategoryBrand.getRecords()).data("total",pageCategoryBrand.getTotal());
    }

    @Override
    public Result removeCB(Integer cid, Integer bid) {
        QueryWrapper<TbCategoryBrand> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id",cid);
        wrapper.eq("brand_id",bid);
        baseMapper.delete(wrapper);
        return Result.ok();
    }

    @Override
    public Result add(Integer cid, Integer bid) {
        QueryWrapper<TbCategoryBrand> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id",cid);
        wrapper.eq("brand_id",bid);
        Integer count = baseMapper.selectCount(wrapper);
        if (count==0){
            TbCategoryBrand categoryBrand = new TbCategoryBrand();
            categoryBrand.setBrandId(bid);
            categoryBrand.setCategoryId(cid);
            baseMapper.insert(categoryBrand);
            return Result.ok();
        }
        return Result.error();
    }

    // 根据查询条件封装模块对象
    private QueryWrapper<TbCategoryBrand> createExample(Map<String, Object> searchMap) {
        QueryWrapper<TbCategoryBrand> wrapper = new QueryWrapper<>();
        if(searchMap!=null) {
            if(searchMap.get("categoryId")!=null)
                wrapper.eq("category_id",searchMap.get("categoryId"));
            if(searchMap.get("brandId")!=null && !"".equals(searchMap.get("brandId")))
                wrapper.like("category_id",searchMap.get("brandId"));
        }
        return wrapper;
    }
}
